package com.ncu.uibroadcast;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

public class MyService extends Service {
    public MyService() {
    }
    //判断停止的标志
    boolean isStop=false;

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }
    public void onCreate(){
        Log.i("TAG","Services onCreate");
        super.onCreate();
    }
    public void onStart(Intent intent,int startId){
        Log.i("TAG","Services onStart");
        super.onStart(intent, startId);
        new Thread(){//新建线程，每隔1秒发送一次广播，同时把i放进intent传出
            public void run(){
                int i=0;
                while(!isStop){
                    Intent intent=new Intent();
                    intent.putExtra("i", i);
                    i++;
                    intent.setAction("com.ncu.uibroadcast.MyReceiver");//action与接收器相同
                    sendBroadcast(intent);
                    Log.i("TAG",String.valueOf(i));
                    try {
                        sleep(1000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        }.start();

    }
    @Override
    public void onDestroy() {
        Log.i("TAG","Services onDestory");
        isStop=true;//即使service销毁线程也不会停止，所以这里通过设置isStop来停止线程
        super.onDestroy();
    }
}
